const rq = require('request-promise')
const log4js = require('log4js');
const fs = require('fs');

var logger = log4js.getLogger();
logger.level = 'debug';

//百度开发者中心的{API Key}和{Secret Key}
var client_id = 'MUcPtsje9zlvXN7cItnbUC1H'
var client_secret = 'WRKeQ4rq85P9yyARMENFT6yeBuV3Mm4N'

//获取token方法
async function getAccessToken(str64) {
  logger.info("getAccessToken")
  var url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret;
  var res = rq(url).then(html => {
    var jsObj = JSON.parse(html)
    var access_token = jsObj.access_token;
    logger.info(access_token)
    //开始分析图片
    // var str64 = getBase64Str()
    // logger.info(str64)
    return analysisPicture(access_token, str64)
  }).catch(err => {
    logger.info(err);
  })
  return res
}
//获取文件的base64值
function getBase64Str() {
  let bitmap = fs.readFileSync('sunflower.jpg');
  let base64str = Buffer.from(bitmap, 'binary').toString('base64'); // base64编码
  return base64str
}
//分析图片方法
async function analysisPicture(access_token, fileStr) {
  request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
  request_url = request_url + "?access_token=" + access_token
  var param = "image=" + fileStr;
  var options = {
    method: 'POST',
    uri: request_url,
    form: {
      image: fileStr
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  };
  var res = rq(options).then(html => {
    logger.info("analysisPicture", html)
    return html;
  }).catch(err => {
    logger.info(err);
  })
  return res
}

module.exports = {
  getAccessToken
}